package com.wink_172.library.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import com.wink_172.library.R;


/**
 * 自定义底部横线的Textview  可适用于Tablayout
 */
public class UnderlineTextView extends AppCompatTextView {

    private final Paint paint01 = new Paint();
    private int underlineHeight = 0;
    private int underLineColor;


    public UnderlineTextView(Context context) {
        this(context, null);
    }

    //通过XML配置但不定义style时会调用这个函数
    public UnderlineTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);


        underLineColor = Color.parseColor("#4bd0ff");

        underlineHeight = dp2px(context, 0);//默认为0
    }

    public int dp2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    //通过XML配置且定义样式时会调用这个函数
    public UnderlineTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    //防止下划线高度大到一定值时会覆盖掉文字，需从写此方法
    @Override
    public void setPadding(int left, int top, int right, int bottom) {
        super.setPadding(left, top, right, bottom + underlineHeight);
    }

    //绘制下划线
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //设置下划线颜色
        paint01.setColor(underLineColor);

        TextPaint paint02 = getPaint();
        float textLength = paint02.measureText(getText().toString());//文字的宽度

        int padding = (int) ((getWidth() - textLength) / 2);

        canvas.drawRect(padding + 5, getHeight() - underlineHeight, getWidth() - padding - 5, getHeight(), paint01);
    }

    /**
     * 更新底部线的高度
     */
    public void updateLine(int height) {
        underlineHeight = height;
        invalidate();//重新绘制
    }

    public void updateLineColor(int color) {
        underLineColor = color;
    }
}

